package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.Result;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.YddUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/ydd_user")
public class YddUserController {
    @Autowired
    private YddUserService yddUserService;

    //用户列表
    @GetMapping("/list")
    private Result page(Integer sex,String username,String mobile,Integer page,Integer limit){
        //查询构造器
        Page<YddUser> pageInfo = new Page<>(page,limit);
        //条件构造器
        LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(sex!=null,YddUser::getSex,sex);
        queryWrapper.like(sex!=null,YddUser::getUsername,username);
        queryWrapper.like(sex!=null,YddUser::getMobile,mobile);
        Page<YddUser> yddUserPage = yddUserService.page(pageInfo, queryWrapper);
        PageResult result = PageResult.answer(yddUserPage.getTotal(), yddUserPage.getSize(), yddUserPage.getCurrent(), yddUserPage.getRecords());
        return Result.ok("",result);
    }

    //用户回显
    @GetMapping("/rowInfo")
    public Result selectById(Integer id){
        log.info("用户回显id:{}",id);
        YddUser yddUser = yddUserService.getById(id);
        return Result.ok("",yddUser);
    }

    //添加用户
    @PostMapping("/add")
    public Result add(@RequestBody YddUser yddUser){
        log.info("新增用户: yddUser{}",yddUser);
        yddUserService.updateById(yddUser);
        return Result.ok("新增成功",null);
    }

    //用户删除
    @GetMapping("/del")
    public Result delete(Integer id){
        log.info("删除用户id: {}",id);
        yddUserService.removeById(id);
        return Result.ok("删除成功",null);
    }
    //用户修改
    @PostMapping("/update")
    public Result update(@RequestBody YddUser yddUser){
        log.info("修改用户: yddUser",yddUser);
        yddUserService.updateById(yddUser);
        return Result.ok("修改成功",null);
    }

}
